package com.marketing.auth.controller;

import com.marketing.auth.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Token管理控制器
 * 提供Token解析和权限验证功能
 */
@RestController
@RequestMapping("/token")
public class TokenController {

    private static final Logger logger = LoggerFactory.getLogger(TokenController.class);

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 解析Token内容
     */
    @PostMapping("/parse")
    public ResponseEntity<Map<String, Object>> parseToken(@RequestHeader("Authorization") String authHeader) {
        logger.info("收到Token解析请求");
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                response.put("success", false);
                response.put("message", "Token格式不正确");
                return ResponseEntity.badRequest().body(response);
            }
            
            String token = authHeader.substring(7);
            
            // 解析Token中的所有信息
            Map<String, Object> tokenInfo = new HashMap<>();
            tokenInfo.put("username", jwtUtil.getUsernameFromToken(token));
            tokenInfo.put("userId", jwtUtil.getUserIdFromToken(token));
            tokenInfo.put("role", jwtUtil.getRoleFromToken(token));
            tokenInfo.put("roles", jwtUtil.getRoleCodesFromToken(token));
            tokenInfo.put("permissions", jwtUtil.getPermissionCodesFromToken(token));
            tokenInfo.put("expirationDate", jwtUtil.getExpirationDateFromToken(token));
            tokenInfo.put("isExpired", jwtUtil.isTokenExpired(token));
            
            // 获取所有Claims（调试用）
            Map<String, Object> allClaims = jwtUtil.getAllClaimsFromToken(token);
            tokenInfo.put("allClaims", allClaims);
            
            response.put("success", true);
            response.put("message", "Token解析成功");
            response.put("data", tokenInfo);
            
            logger.info("Token解析成功，用户: {}, 权限数量: {}", 
                    tokenInfo.get("username"), 
                    tokenInfo.get("permissions") != null ? ((Set<?>)tokenInfo.get("permissions")).size() : 0);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("Token解析失败，异常: {}", e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", "Token解析失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 检查用户是否拥有指定权限
     */
    @PostMapping("/check-permission")
    public ResponseEntity<Map<String, Object>> checkPermission(
            @RequestHeader("Authorization") String authHeader,
            @RequestParam String permission) {
        
        logger.info("收到权限检查请求，权限: {}", permission);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                response.put("success", false);
                response.put("message", "Token格式不正确");
                return ResponseEntity.badRequest().body(response);
            }
            
            String token = authHeader.substring(7);
            boolean hasPermission = jwtUtil.hasPermission(token, permission);
            
            response.put("success", true);
            response.put("message", "权限检查完成");
            response.put("data", Map.of(
                    "permission", permission,
                    "hasPermission", hasPermission,
                    "username", jwtUtil.getUsernameFromToken(token)
            ));
            
            logger.info("权限检查完成，用户: {}, 权限: {}, 拥有: {}", 
                    jwtUtil.getUsernameFromToken(token), permission, hasPermission);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("权限检查失败，权限: {}, 异常: {}", permission, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", "权限检查失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }

    /**
     * 检查用户是否拥有指定角色
     */
    @PostMapping("/check-role")
    public ResponseEntity<Map<String, Object>> checkRole(
            @RequestHeader("Authorization") String authHeader,
            @RequestParam String role) {
        
        logger.info("收到角色检查请求，角色: {}", role);
        
        Map<String, Object> response = new HashMap<>();
        
        try {
            if (authHeader == null || !authHeader.startsWith("Bearer ")) {
                response.put("success", false);
                response.put("message", "Token格式不正确");
                return ResponseEntity.badRequest().body(response);
            }
            
            String token = authHeader.substring(7);
            boolean hasRole = jwtUtil.hasRole(token, role);
            
            response.put("success", true);
            response.put("message", "角色检查完成");
            response.put("data", Map.of(
                    "role", role,
                    "hasRole", hasRole,
                    "username", jwtUtil.getUsernameFromToken(token),
                    "userRoles", jwtUtil.getRoleCodesFromToken(token)
            ));
            
            logger.info("角色检查完成，用户: {}, 角色: {}, 拥有: {}", 
                    jwtUtil.getUsernameFromToken(token), role, hasRole);
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            logger.error("角色检查失败，角色: {}, 异常: {}", role, e.getMessage(), e);
            
            response.put("success", false);
            response.put("message", "角色检查失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}